import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.util.TypedValue
import android.util.TypedValue.COMPLEX_UNIT_SP
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.hiray.exception.ExpiredException
import com.hiray.exception.XQException
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.mvp.model.ResponseWrapper
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.android.schedulers.AndroidSchedulers.mainThread
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import java.io.File


fun File.installIntent(context: Context) = run {
    val intent = Intent(Intent.ACTION_VIEW)
//    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//        intent.action = Intent.ACTION_INSTALL_PACKAGE
//        intent.setDataAndType(Uri.fromFile(this), "application/vnd.android.package-archive")
//        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
//    } else {
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
//        intent.setDataAndType(FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, this),
//                "application/vnd.android.package-archive")
//    }
//    intent.`package` = "com.android.packageinstaller"

    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
        intent.setDataAndType(
            Uri.fromFile(this.absoluteFile),
            "application/vnd.android.package-archive"
        )
    else {
        intent.setDataAndType(
            FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, this),
            "application/vnd.android.package-archive"
        )
    }
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    intent
}

val Number.dp: Int get() = (this.toInt() * Resources.getSystem().displayMetrics.density).toInt()

//val Number.sp: Float get() = TypedValue.applyDimension(COMPLEX_UNIT_SP, this.toFloat(),Resources.getSystem().displayMetrics)/*(this.toFloat() * Resources.getSystem().displayMetrics.scaledDensity)*/

fun Number.sp(context: Context): Float =
    TypedValue.applyDimension(COMPLEX_UNIT_SP, this.toFloat(), context.resources.displayMetrics)

val View.centerX: Float get() = this.x + this.width / 2

fun View.setVisible() {
    this.visibility = View.VISIBLE
}

fun View.setGone() {
    if (this.visibility != View.GONE)
        this.visibility = View.GONE
}

fun View.setInvisible() {
    if (this.visibility == View.VISIBLE)
        this.visibility = View.INVISIBLE
}

fun androidx.fragment.app.Fragment?.quickStartActivity(clazz: Class<*>) =
    this?.startActivity(Intent(this.context, clazz))

fun AppCompatActivity.quickStartActivity(clazz: Class<*>) = this.startActivity(Intent(this, clazz))

fun AppCompatActivity.suicideAfterTransition() = ActivityCompat.finishAfterTransition(this)

fun <T> Observable<T>.androidSchedule() = this.subscribeOn(Schedulers.io()).observeOn(mainThread())

fun <T> Flowable<T>.androidSchedule() = this.subscribeOn(Schedulers.io()).observeOn(mainThread())

fun <T> Observable<ResponseWrapper<T>>.responseFunc() =
    this.flatMap(Function<ResponseWrapper<T>, ObservableSource<T>> { t ->
        Observable.create {
            if (t.isOk())
                it.onNext(t.data)
            else {
                if (t.isAuthExpired())
                    it.onError(ExpiredException(t.errMsg))
                else it.onError(XQException(t.errMsg))
            }
        }
    })
//
//fun <T> Observable<T>.autoDispose(scopeProvider: AndroidLifecycleScopeProvider) =
//    `as`(autoDisposable(scopeProvider))

fun Observable<ResponseWrapper<Void>>.responseVoidFunc() =
    this.flatMap(Function<ResponseWrapper<Void>, ObservableSource<Void>> { t ->
        Observable.create {
            if (t.isOk())
                it.onComplete()
            else
                if (t.isAuthExpired())
                    it.onError(ExpiredException(t.errMsg))
                else it.onError(XQException(t.errMsg))
        }
    })

//maybe 主要是用来进行本地数据库查找
//比如某个用户是否存在
fun <T> Maybe<T>.androidSchedule() = this.observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())

//fun <T> AppCompatActivity.androidAutoDispose() = autoDisposable<T>(AndroidLifecycleScopeProvider.from(this))


fun Context.copy(text: String) {
    val clipManager = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    clipManager.primaryClip = ClipData.newPlainText("", text)
}


/***********************************/
